import axios from 'axios'
import { Message } from 'element-ui'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'

const service = axios.create({
  baseURL: 'https://tdiot.cloud/',
  // baseURL: '/api',
  timeout: 30000
})
service.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    config.headers['databasename'] = 'DW_DLYHSCV3';
    config.headers['organizationlist'] = 'DLYNJD';
    config.headers['organizationno'] = 'DLYNJD';
    config.headers['sysdatabasename'] = 'DW_DLYHSCV3';
    config.headers['systemmark'] = 'SC';
    config.headers['virtualsystemno'] = 'SY-YY';
    config.headers['accesstoken'] = getToken()
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code == -3) {
      removeToken();
      router.push({ path: '/index' })
    }
    return res
  },
  error => {
    let err = JSON.parse(JSON.stringify(error));
    if (err.response) {
      switch (err.response.status) {
        case 500:
          Message.error('请求异常!')
          break;
        case 503:
          Message.error('服务器更新中!')
          break;
        case 404:
          Message.error('未找到访问接口!')
        default:
          Message.error('请求异常!')
          break;
      }
    }
    return Promise.reject(error)
  }
)
//特殊处理get请求的condition
export function getCondition(data = {}) {
  console.log(data)
  let condition = [];
  for (let key in data) {
    if (data[key]) {
      let obj = {
        paramName: key,
        sign: "like",
        value: data[key]
      };
      condition.push(obj)
    }
  }
  return condition.length == 0 ? null : condition
}
// 封装get请求
export function get(url, params = {}) {
  let str = '';
  let queryurl = ''
  let condition = ''
  for (let key in params) {
    if (key == 'condition') {
      let obj = getCondition(params['condition'])
      condition = encodeURIComponent(JSON.stringify(obj))
    } else {
      str += `${key}=${params[key]}&`
    }
  }
  if (condition) {
    queryurl = str || condition ? '?' + str + 'condition=' + condition : '';
  } else {
    queryurl = str ? '?' + str : '';
  }
  return url + queryurl;
}
export default service
